<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="500px">
    <template #header>
      <h4>{{ drawerProps.title }}物料</h4>
    </template>
    <template #default>
      <el-form
        ref="ruleFormRef"
        label-width="100px"
        label-suffix=" :"
        :rules="rules"
        :disabled="drawerProps.isView"
        :model="drawerProps.row"
        :hide-required-asterisk="drawerProps.isView"
      >
        <el-form-item label="物料编码" prop="materialCode">
          <el-input
            v-model="drawerProps.row.materialCode"
            placeholder="请输入物料编码"
            clearable
            :disabled="drawerProps.title === '编辑'"
          />
        </el-form-item>

        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="drawerProps.row.materialName" placeholder="请输入物料名称" clearable />
        </el-form-item>

        <el-form-item label="物料群组" prop="groupId">
          <el-select v-model="drawerProps.row.groupId" placeholder="请选择物料群组" clearable style="width: 100%">
            <el-option v-for="group in materialGroupOptions" :key="group.value" :label="group.label" :value="group.value" />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="drawerProps.row.specification" placeholder="请输入规格" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="drawerProps.row.model" placeholder="请输入型号" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unit">
              <el-select v-model="drawerProps.row.unit" placeholder="请选择单位" clearable style="width: 100%">
                <el-option label="个" value="个" />
                <el-option label="件" value="件" />
                <el-option label="套" value="套" />
                <el-option label="台" value="台" />
                <el-option label="米" value="米" />
                <el-option label="千克" value="千克" />
                <el-option label="吨" value="吨" />
                <el-option label="升" value="升" />
                <el-option label="立方米" value="立方米" />
                <el-option label="平方米" value="平方米" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标准成本" prop="standardCost">
              <el-input-number
                v-model="drawerProps.row.standardCost"
                placeholder="请输入标准成本"
                :precision="2"
                :min="0"
                :max="999999999"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="状态" prop="status" v-if="drawerProps.title !== '新增'">
          <el-radio-group v-model="drawerProps.row.status">
            <el-radio value="ACTIVE">启用</el-radio>
            <el-radio value="INACTIVE">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="drawerProps.row.description"
            type="textarea"
            placeholder="请输入物料描述"
            :autosize="{ minRows: 3, maxRows: 6 }"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Material } from "@/api/modules/material";
import { getActiveMaterialGroups } from "@/api/modules/materialGroup";

const rules = reactive({
  materialCode: [{ required: true, message: "请输入物料编码", trigger: "blur" }],
  materialName: [{ required: true, message: "请输入物料名称", trigger: "blur" }],
  unit: [{ required: true, message: "请选择计量单位", trigger: "change" }],
  groupId: [{ required: true, message: "请选择物料群组", trigger: "change" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Material.MaterialListItem>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 物料群组选项
const materialGroupOptions = ref<Array<{ label: string; value: string }>>([]);

// 表单引用
const ruleFormRef = ref<FormInstance>();

// 获取物料群组选项
const getMaterialGroupOptions = async () => {
  try {
    const { data } = await getActiveMaterialGroups();
    materialGroupOptions.value = data.map(item => ({
      label: item.groupName,
      value: item.id
    }));
  } catch (error) {
    console.error("获取物料群组选项失败:", error);
  }
};

// 接收父组件参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  getMaterialGroupOptions();

  // 设置默认值
  if (params.title === "新增") {
    drawerProps.value.row = {
      materialCode: "",
      materialName: "",
      specification: "",
      model: "",
      unit: "",
      groupId: "",
      standardCost: undefined,
      description: "",
      status: "ACTIVE"
    };
  }
};

// 提交数据
const handleSubmit = async () => {
  if (!ruleFormRef.value) return;

  const valid = await ruleFormRef.value.validate().catch(() => false);
  if (!valid) return;

  try {
    await drawerProps.value.api!(drawerProps.value.row);
    ElMessage.success({ message: `${drawerProps.value.title}物料成功！` });
    drawerProps.value.getTableList!();
    drawerVisible.value = false;
  } catch (error) {
    ElMessage.error({ message: `${drawerProps.value.title}物料失败！` });
  }
};

// 页面加载时获取物料群组选项
// onMounted(() => {
//   getMaterialGroupOptions();
// });

defineExpose({
  acceptParams
});
</script>

<style scoped>
.el-drawer__header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}
</style>